package com.cyy.hardwarecoding.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.cyy.hardwarecoding.R;
import com.orhanobut.logger.Logger;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class GPSActivity extends AppCompatActivity implements LocationListener{

    private LocationManager locationManager;
    @BindView(R.id.tv_latitude) TextView tv_latitude;
    @BindView(R.id.tv_longitude) TextView tv_longitude;
    @BindView(R.id.tv_accuracy) TextView tv_accuracy;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gps);
        init();
        bindData();
    }

    private void init(){
        ButterKnife.bind(this);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    private void bindData(){
    }

    @Override
    protected void onResume() {
        super.onResume();
        GPSActivityPermissionsDispatcher.startLocationWithPermissionCheck(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }


    @SuppressLint("MissingPermission")
    @NeedsPermission(Manifest.permission.ACCESS_FINE_LOCATION)
    void startLocation(){
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        List<String> enabledProviders = locationManager.getProviders(criteria, true);
        if(enabledProviders != null){
            for (String providerStr: enabledProviders) {
                Logger.i("提供者:"+providerStr);
                locationManager.requestLocationUpdates(providerStr, 0, 0, this);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        GPSActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.ACCESS_FINE_LOCATION)
    void showRationaleForLocation(final PermissionRequest request){
        new AlertDialog.Builder(this)
                .setMessage("需要定位权限才能获取地理信息")
                .setPositiveButton(R.string.allow, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .create()
                .show();
    }

    @OnPermissionDenied(Manifest.permission.ACCESS_FINE_LOCATION)
    void OnLocationPermissionDenied(){
        Toast.makeText(this, "获取取位置权限失败", Toast.LENGTH_SHORT).show();
        finish();
    }

    @OnNeverAskAgain(Manifest.permission.ACCESS_FINE_LOCATION)
    void OnNeverAskForLocation(){
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("请到设置中开启位置权限")
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .create()
                .show();
    }


    /**
     * LocationListener
     * ***************************************************************/
    @Override
    public void onLocationChanged(Location location) {
        tv_latitude.setText(String.format(getString(R.string.latitude), location.getLatitude()));
        tv_longitude.setText(String.format(getString(R.string.longitude), location.getLongitude()));
        tv_accuracy.setText(String.format(getString(R.string.accuracy), location.getAccuracy()));
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status){
                case LocationProvider.AVAILABLE:{
                    Logger.d(provider+":在线");
                } break;
                case LocationProvider.OUT_OF_SERVICE:{
                    Logger.d(provider+":掉线");
                } break;
                case LocationProvider.TEMPORARILY_UNAVAILABLE:{
                    Logger.d(provider+":暂时离线");
                }
                default:{}
            }
    }

    @Override
    public void onProviderEnabled(String provider) {
        Logger.d(provider+"is enabled");
    }

    @Override
    public void onProviderDisabled(String provider) {
        Logger.d(provider+"is disabled");

    }
}
